package com.itheima.stock.algorithm;


import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.joda.time.DateTime;

import java.util.Collection;
import java.util.Date;

/**
 * @Description 公共数据库精准匹配逻辑
 */
public class CommonDbPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    /**
     * m-$->{2021..2022}
     * @param collection 当前逻辑表对应的所有的库名称集合： m-2021,m-2022
     * @param preciseShardingValue 封装了cur_time片键相关的信息
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        //获取逻辑表名称
        String logicTableName = preciseShardingValue.getLogicTableName();
        //获取片键名
        String columnName = preciseShardingValue.getColumnName();
        //获取片键值
        Date curTime = preciseShardingValue.getValue();
        //根据传入的日期，获取对应的年，然后从数据库集合中过滤即可
        int year = new DateTime(curTime).getYear();
        //查找year对应的数据库
        String dsName = collection.stream().filter(dbName -> dbName.endsWith(year + "")).findFirst().get();
        return dsName;
    }
}
